﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AnalisisDeRiesgos.Models;
using AnalisisDeRiesgos.Models.Danger;

namespace AnalisisDeRiesgos.Controllers
{
    public class DangerController : Controller
    {
        //
        // GET: /Danger/

        public ActionResult Index()
        {
            if (!Utils.HasPrivilege(Convert.ToInt32(Session["userid"]), Privileges.AreaSecurity))
                return RedirectToAction("LogOn", "User");

            SearchDangerModel model = new SearchDangerModel();

            return View(model);
        }

        [HttpPost]
        public ActionResult Index(SearchDangerModel model)
        {
            if (ModelState.IsValid)
                model.SearchDanger();

            return View(model);
        }

        //
        // GET: /Danger/Details/5

        public ActionResult Details(int ?id)
        {
            if (id == null)
                RedirectToAction("Index");

            int userId = Convert.ToInt32(Session["userid"]);

            if (!Utils.HasPrivilege(userId, Privileges.AreaSecurity))
                return RedirectToAction("LogOn", "User");

            try
            {
                DetailsDangerModel model = new DetailsDangerModel(id.Value);

                if (Utils.MustHavePrivilege(userId, Privileges.AreaSecurity))
                {
                    if (EditDangerModel.GetDangerById(id.Value).activity.area.process.management.user.CI != userId)
                        return View("Error", new ErrorModel { Message = "Tu no tienes permiso para ver este peligro" });
                }

                return View(model);
            }
            catch (Exception ex)
            {
                return View("Error", new ErrorModel { Message = ex.Message });
            }
        }

        //
        // GET: /Danger/Create

        public ActionResult Create()
        {
            if (!Utils.HasPrivilege(Convert.ToInt32(Session["userid"]), Privileges.Employe))
                return RedirectToAction("LogOn", "User");

            RegisterDangerModel model = new RegisterDangerModel();

            return View(model);
        } 

        //
        // POST: /Danger/Create

        [HttpPost]
        public ActionResult Create(RegisterDangerModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return View();
                }

                model.Save();
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return View(model);
            }
        }
        
        //
        // GET: /Danger/Edit/5
 
        public ActionResult Edit(int? id)
        {
            if (id == null)
                return RedirectToAction("Index");
            
            int userId = Convert.ToInt32(Session["userid"]);

            if (!(Utils.MustHavePrivilege(userId, Privileges.AreaSecurity) || Utils.MustHavePrivilege(userId, Privileges.GeneralSecurity)))
                return RedirectToAction("LogOn", "User");
            
            try
            {
                EditDangerModel model = new EditDangerModel(id.Value);

                if (Utils.MustHavePrivilege(userId, Privileges.AreaSecurity))
                {
                    if (EditDangerModel.GetDangerById(id.Value).activity.area.process.management.user.CI != userId)
                        return View("Error", new ErrorModel { Message = "Tu no tienes permiso para editar este peligro" });
                }

                return View(model);
            }
            catch (Exception ex)
            {
                return View("Error", new ErrorModel { Message = ex.Message });
            }
        }

        //
        // POST: /Danger/Edit/5

        [HttpPost]
        public ActionResult Edit(EditDangerModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                    return View(model);

                model.Save();
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
            }

            return View(model);
        }

        //
        // GET: /Danger/Delete/5
 
        public ActionResult Delete(int ?id)
        {
            if (id == null)
                return RedirectToAction("Index");

            int userId = Convert.ToInt32(Session["userid"]);

            if (!Utils.HasPrivilege(userId, Privileges.AreaSecurity))
                return RedirectToAction("LogOn", "User");

            try
            {
                if (Utils.MustHavePrivilege(userId, Privileges.AreaSecurity))
                {
                    if (EditDangerModel.GetDangerById(id.Value).activity.area.process.management.user.CI != userId)
                        return View("Error", new ErrorModel { Message = "Tu no tienes permiso para eliminar este peligro" });
                }

                DetailsDangerModel model = new DetailsDangerModel(id.Value);

                return View(model);
            }
            catch (Exception ex)
            {
                return View("Error", new ErrorModel { Message = ex.Message });
            }
        }

        //
        // POST: /Danger/Delete/5

        [HttpPost]
        public ActionResult Delete(int id)
        {
            try
            {
                DetailsDangerModel model = new DetailsDangerModel(id);
                try
                {
                    model.DeleteDanger();
                    return RedirectToAction("Index");
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.Message);
                }

                return View(model);
            }
            catch
            {
                return View();
            }
        }

        public ActionResult GetProcessByManagementId(int? id)
        {
            IEnumerable<SelectListItem> list;

            if (id == null)
                list = new List<SelectListItem>();
            else
                list = Utils.FillProcessList(id.Value);

            return Json(list, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetAreaByProcessId(int? id)
        {
            IEnumerable<SelectListItem> list;

            if (id == null)
                list = new List<SelectListItem>();
            else
                list = Utils.FillAreaList(id.Value);

            return Json(list, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetActivityByAreaId(int? id)
        {
            IEnumerable<SelectListItem> list;

            if (id == null)
                list = new List<SelectListItem>();
            else
                list = Utils.FillActivityList(id.Value);

            return Json(list, JsonRequestBehavior.AllowGet);
        }

        //Para las busquedas, agrega el elemento Todos
        public ActionResult GetProcessByManagementId2(int? id)
        {
            List<SelectListItem> list;

            if (id == null)
                list = new List<SelectListItem>();
            else
                list = Utils.FillProcessList(id.Value);
            list.Add(new SelectListItem { Text = "Todos", Value = "0", Selected = true });

            return Json(list, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetAreaByProcessId2(int? id)
        {
            List<SelectListItem> list;

            if (id == null)
                list = new List<SelectListItem>();
            else
                list = Utils.FillAreaList(id.Value);
            list.Add(new SelectListItem { Text = "Todos", Value = "0", Selected = true });
            return Json(list, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetActivityByAreaId2(int? id)
        {
            List<SelectListItem> list;

            if (id == null)
                list = new List<SelectListItem>();
            else
                list = Utils.FillActivityList(id.Value);
            list.Add(new SelectListItem { Text = "Todos", Value = "0", Selected = true });

            return Json(list, JsonRequestBehavior.AllowGet);
        }
    }
}
